package com.mico.xchange.chaoex.service;

import com.mico.micochange.common.TimeConverterUtil;
import com.mico.xchange.Exchange;
import com.mico.xchange.chaoex.ChaoexAuthenticated;
import com.mico.xchange.chaoex.ChaoexExchange;
import com.mico.xchange.chaoex.dto.ChaoexResult;
import com.mico.xchange.exceptions.ExchangeException;
import com.mico.xchange.service.BaseExchangeService;
import com.mico.xchange.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import si.mazi.rescu.ParamsDigest;
import si.mazi.rescu.RestProxyFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChaoexBaseService extends BaseExchangeService implements BaseService {

  protected final Logger LOG = LoggerFactory.getLogger(getClass());

  protected final String apiKey;
  protected final ChaoexAuthenticated chaoex;
  protected final ParamsDigest signatureCreator;

  protected ChaoexBaseService(Exchange exchange) {

    super(exchange);
    this.chaoex =
        RestProxyFactory.createProxy(
            ChaoexAuthenticated.class,
            exchange.getExchangeSpecification().getSslUri(),
            getClientConfig());
    this.apiKey = exchange.getExchangeSpecification().getApiKey();
    this.signatureCreator =
        ChaoexHmacDigest.createInstance(exchange.getExchangeSpecification().getSecretKey());
  }


  /**
   * After period of time, the deltaServerTime may not accurate again. Need to catch the "Timestamp
   * for this request was 1000ms ahead" exception and refresh the deltaServerTime.
   */
  public void refreshTimestamp() {
    ((ChaoexExchange) exchange).clearDeltaServerTime();
  }


  protected <R> R checkResult(ChaoexResult<R> chaoexResult) {
   if (!chaoexResult.isSuccess()) {
      String chaoexError = chaoexResult.getError();
      if (chaoexError.length() == 0) {
        throw new ExchangeException("Missing error message");
      } else {
        throw new ExchangeException(chaoexError);
      }
    }
    return chaoexResult.getResult();
  }

  public String getTimestamp() throws IOException {
    return TimeConverterUtil.getCurrentUtcTime();
  }
}
